package com.viewpagerindicator.sample.util;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.util.Log;

import com.viewpagerindicator.sample.R;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by zhao on 2015/11/9.
 */
public class BluetoothUtils {
    private Context context;
    private BluetoothAdapter adapter;
    public BluetoothUtils(Context context,BluetoothAdapter adapter){
        this.context=context;
        this.adapter=adapter;
    }
    public List<BluetoothDevice> listDevice() throws NoBlueToothException,BlueToothCloseException,BlueToothNopairException{
        //判断BluetoothAdapter对象是否为空，如果为空，则表明本机没有蓝牙设备
        if(adapter != null){
            //有蓝牙
            if(!adapter.isEnabled()){
                //未打开蓝牙
                throw new BlueToothCloseException(this.context.getString(R.string.error_blute_close));
            }else{
                List<BluetoothDevice> list=new ArrayList<>();
                //蓝牙一打开,获取已经配对的蓝牙
                Set<BluetoothDevice> devices = adapter.getBondedDevices();
                if(devices.size()>0){
                    for(Iterator iterator = devices.iterator();iterator.hasNext();){
                        //得到BluetoothDevice对象,也就是说得到配对的蓝牙适配器
                        BluetoothDevice device = (BluetoothDevice)iterator.next();
                        //得到远程蓝牙设备的地址
                        Log.d("mytag", device.getAddress());
                        list.add(device);
                    }
                    return list;
                }else{
                    throw new BlueToothNopairException(this.context.getString(R.string.error_noblue_pair));
                }
            }
        }else{
            //没有蓝牙
            throw new NoBlueToothException(this.context.getString(R.string.error_noblute));
        }
    }
    //用到的异常类
    public class NoBlueToothException extends Exception{
        public NoBlueToothException(String detailMessage) {
            super(detailMessage);
        }
    }
    public class BlueToothCloseException extends Exception{
        public BlueToothCloseException(String detailMessage) {
            super(detailMessage);
        }
    }
    public class BlueToothNopairException extends Exception{
        public BlueToothNopairException(String detailMessage) {
            super(detailMessage);
        }
    }
}
